package com.yiqi.zhiyuan.feature.certification.view;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.suozhang.framework.framework.BaseActivity;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.common.widget.citypicker.adapter.CityListAdapter;
import com.yiqi.zhiyuan.common.widget.citypicker.adapter.ResultListAdapter;
import com.yiqi.zhiyuan.common.widget.citypicker.db.DBManager;
import com.yiqi.zhiyuan.common.widget.citypicker.view.SideLetterBar;
import com.yiqi.zhiyuan.entity.vo.BrandChildVO;
import com.yiqi.zhiyuan.entity.vo.BrandModelVO;
import com.yiqi.zhiyuan.entity.vo.CarBrandVO;
import com.yiqi.zhiyuan.feature.certification.contract.BrandContract;
import com.yiqi.zhiyuan.feature.certification.dependencies.brand.BrandPresenterModule;
import com.yiqi.zhiyuan.feature.certification.dependencies.brand.DaggerBrandComponent;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * author zaaach on 2016/1/26.
 */
public class CityPickerActivity extends BaseActivity implements View.OnClickListener, BrandContract.View, AdapterView.OnItemClickListener, CityListAdapter.OnCityClickListener, BrandPopup.Callback {
    public static final int REQUEST_CODE_PICK_CITY = 2333;
    public static final String KEY_PICKED_CITY = "picked_city";
    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;
    private EditText searchBox;
    private ImageView clearBtn;
    private ViewGroup emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<CarBrandVO> mAllCities;
    private String mBrandStr;
    DBManager dbManager;
    @Inject
    BrandContract.Presenter mPresenter;


    @Override
    public void initData() {
        dbManager = new DBManager(this);
        initToolBar(mToolbar, "选择城市", true, true);

        initView();
        mPresenter.doQueryCarBrands();
    }

    @Override
    public void initView() {
        mResultAdapter = new ResultListAdapter(CityPickerActivity.this, null);
        mListView = findViewById(R.id.listview_all_city);
        TextView overlay = findViewById(R.id.tv_letter_overlay);
        mLetterBar = findViewById(R.id.side_letter_bar);
        searchBox = findViewById(R.id.et_search);
        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mBrandStr = mResultAdapter.getItem(position).getBname();
                mPresenter.doQueryCarBrandModel(mResultAdapter.getItem(position).getBcode());
            }
        });

        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });


        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);
                    List<CarBrandVO> result = dbManager.searchCity(keyword, mAllCities);
                    if (result == null || result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                        mResultListView.setAdapter(mResultAdapter);
                    }
                }
            }
        });


        clearBtn = findViewById(R.id.iv_search_clear);
        clearBtn.setOnClickListener(this);

    }

    private void back(String baseBo) {
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, baseBo);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search_clear:
                searchBox.setText("");
                clearBtn.setVisibility(View.GONE);
                emptyView.setVisibility(View.GONE);
                mResultListView.setVisibility(View.GONE);
                break;
//            case R.id.back:
//                finish();
//                break;
            default:
                break;
        }
    }


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_city_list;
    }

    @Override
    protected void initInjector() {
        DaggerBrandComponent.builder().brandPresenterModule(new BrandPresenterModule(this)).build().inject(this);
    }


    @Override
    public void showQueryCarBrandsSuccess(List<CarBrandVO> data) {
        mAllCities = data;
        mCityAdapter = new CityListAdapter(CityPickerActivity.this, mAllCities);
        mCityAdapter.setOnCityClickListener(this);
        mListView.setAdapter(mCityAdapter);

    }

    @Override
    public void showQueryCarBrandModelSuccess(List<BrandChildVO> data) {
        if (data != null && data.size() > 0) {
            BrandPopup brandPopup = new BrandPopup(this);
            brandPopup.initPopupWindow(mListView, generateData(data));
            brandPopup.setCallback(this);
        } else {
            showMsg("没有更多数据");
        }

    }

    @Override
    public void showError(String errorMsg) {
        showMsg(errorMsg);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mBrandStr = mAllCities.get(position).getBname();
        mPresenter.doQueryCarBrandModel(mAllCities.get(position).getBcode());
    }

    @Override
    public void onCityClick(CarBrandVO data) {
        mBrandStr = data.getBname();
        mPresenter.doQueryCarBrandModel(data.getBcode());
    }

    private ArrayList<MultiItemEntity> generateData(List<BrandChildVO> data) {
        ArrayList<MultiItemEntity> res = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            BrandChildVO lv0 = data.get(i);
            if (lv0 != null && lv0.getCarModelList() != null) {
                for (int j = 0; j < lv0.getCarModelList().size(); j++) {
                    BrandModelVO lv1 = lv0.getCarModelList().get(j);
                    lv0.addSubItem(lv1);
                }
            }
            res.add(lv0);
        }
        return res;
    }

    @Override
    public void getStr(String model) {
        Intent intent = new Intent();
        intent.putExtra("brand", mBrandStr);
        intent.putExtra("model", model);
        setResult(-1, intent);
        finish(); //结束当前的activity的生命周期
    }
}
